package com.ruoyi.system.service.impl;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.MktPeopleMapper;
import com.ruoyi.system.mapper.MktProductMapper;
import com.ruoyi.system.mapper.MktWinMapper;
import com.ruoyi.system.service.IMktRewardService;
import com.ruoyi.system.service.IMktStatisticsService;
import com.ruoyi.system.util.LotteryUtil;
import com.ruoyi.system.domain.vo.MktActivityVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.mapper.MktActivityMapper;
import com.ruoyi.system.service.IMktActivityService;


@Service
public class MktActivityServiceImpl extends ServiceImpl<MktActivityMapper, MktActivity> implements IMktActivityService {


    @Autowired
    private IMktStatisticsService mktStatisticsService;
    @Autowired
    private MktPeopleMapper mktPeopleMapper;
    @Autowired
    private IMktRewardService mktRewardService;
    @Autowired
    private MktWinMapper mktWinMapper;
    @Autowired
    private MktProductMapper mktProductMapper;

    /**
     * 查询营销活动管理列表
     *
     * @param mktActivity 营销活动管理
     * @return 营销活动管理
     */
    @Override
    public List<MktActivity> selectMktActivityList(MktActivity mktActivity) {
        return getBaseMapper().selectMktActivityList(mktActivity);
    }

    @Override
    public void updateById(MktActivityVo mktActivityVo) {

        //拿到对象,将mktActivityVo中的展示位置属性变成字符串
        String[] displayPosition = mktActivityVo.getDisplayPosition();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < displayPosition.length; i++) {
            if (i < displayPosition.length-1){
                stringBuilder.append(displayPosition[i]).append(",");
            }else {
                stringBuilder.append(displayPosition[i]);
            }
        }
        String s = stringBuilder.toString();

        MktActivity mktActivity = new MktActivity();
        mktActivity.setId(mktActivityVo.getId());
        mktActivity.setName(mktActivityVo.getName());
        mktActivity.setNum(mktActivityVo.getNum());
        mktActivity.setDisplayPosition(s);
        mktActivity.setPicture(mktActivityVo.getImage());
        mktActivity.setLink(mktActivityVo.getLink());
        mktActivity.setBeginTime(mktActivityVo.getBeginTime());
        mktActivity.setEndTime(mktActivityVo.getEndTime());
        mktActivity.setRule(mktActivityVo.getRule());
        mktActivity.setState(mktActivityVo.getState());
        //修改的时候也需要修改
        MktStatistics mktStatistics = new MktStatistics();
        mktStatistics.setId(mktActivityVo.getId());
        mktStatistics.setName(mktActivityVo.getName());
        mktStatistics.setBeginTime(mktActivityVo.getBeginTime());
        mktStatistics.setEndTime(mktActivityVo.getEndTime());
        mktStatistics.setStatus(Long.valueOf(mktActivityVo.getState()));

        mktStatisticsService.updateById(mktStatistics);

        super.updateById(mktActivity);

    }

    @Override
    public void save(MktActivityVo mktActivityVo) {
        //拿到对象,将mktActivityVo中的展示位置属性变成字符串
        String[] displayPosition = mktActivityVo.getDisplayPosition();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < displayPosition.length; i++) {
            if (i < displayPosition.length-1){
                stringBuilder.append(displayPosition[i]).append(",");
            }else {
                stringBuilder.append(displayPosition[i]);
            }
        }
        String s = stringBuilder.toString();

        Date date = new Date();

        MktActivity mktActivity = new MktActivity();
        mktActivity.setName(mktActivityVo.getName());
        mktActivity.setNum(mktActivityVo.getNum());
        mktActivity.setDisplayPosition(s);
        mktActivity.setCreateTime(date);
        mktActivity.setPicture(mktActivityVo.getImage());
        mktActivity.setLink(mktActivityVo.getLink());
        mktActivity.setBeginTime(mktActivityVo.getBeginTime());
        mktActivity.setEndTime(mktActivityVo.getEndTime());
        mktActivity.setRule(mktActivityVo.getRule());
        mktActivity.setState(mktActivityVo.getState());

        //在创建活动对象时候,也需要保存在营销统计表表中
        MktStatistics mktStatistics = new MktStatistics();
        mktStatistics.setName(mktActivityVo.getName());
        //设置创建时间
        mktStatistics.setCreateTime(date);
        mktStatistics.setBeginTime(mktActivityVo.getBeginTime());
        mktStatistics.setEndTime(mktActivityVo.getEndTime());
        //刚创建活动的参与人数是0,总金额也应该是0
        mktStatistics.setPeopleNum(0L);
        mktStatistics.setMoneyTotal(0L);
        //设置状态
        mktStatistics.setStatus(Long.valueOf(mktActivityVo.getState()));
        mktStatisticsService.save(mktStatistics);

        super.save(mktActivity);

    }

    @Override
    public MktReward lottery(Long actId, LoginUser loginUser) {
        //完成抽奖
        //需要判断用户在该活动下是否有抽奖次数
        //获取该用户
        SysUser user = loginUser.getUser();
        //在用户表中去查询该对象
        List<MktPeople> mktPeopleList = mktPeopleMapper.selectList(new LambdaQueryWrapper<MktPeople>().eq(MktPeople::getUserId, user.getUserId()));
        //遍历这个集合
        //标记
        int count = 0;
        MktPeople people = new MktPeople();
        for (MktPeople mktPeople : mktPeopleList) {
            Long joinActivity = mktPeopleMapper.isJoinActivity(mktPeople.getId());
            if (actId.equals(joinActivity)){
                //如果相等那么就说明该用户参与了该活动,就是该对象
                people = mktPeople;
                count++;
            }
        }

        //判断标识符
        if (count == 0){
            //如果标识符等于0那么就说明该用户没有参与该抽奖活动
            throw new ServiceException("请参与活动完成任务获得抽奖次数");
        }

        //没有次数就给出提示没有抽奖次数
        if (people.getSurplusDraw() == 0){
            throw new ServiceException("用户的抽奖次数为0,需要去完成任务");
        }

        //获取该活动下的所以奖励对象
        List<MktReward> list = mktRewardService.list();
        //遍历概率按照顺序放入概率集合中
        List<Double> doubles = new ArrayList<>();
        List<MktReward> mktRewardList = new ArrayList<>();
        for (MktReward reward : list) {
            doubles.add(Double.valueOf(reward.getProbability()));
            mktRewardList.add(reward);
        }
        //如果存在抽奖次数,通过抽奖工具,就完成抽奖,抽奖次数-1
        MktReward mktReward = mktRewardList.get(LotteryUtil.lottery(doubles));
        //减少抽奖次数
        people.setSurplusDraw(people.getSurplusDraw()-1);
        //判断奖励,如果不是谢谢参与,在奖励明细中增加记录,然后对象中奖也需要增加次数
        if (!"谢谢参与".equals(mktReward.getName())){

            //在明细表中增加记录
            MktWin mktWin = new MktWin();
            mktWin.setStatisticsId(actId);
            mktWin.setPeopleId(people.getId());
            mktWin.setWinningTime(new Date());
            mktWin.setReward(mktReward.getId());
            mktWinMapper.insert(mktWin);
            //增减用户的中奖记录
            people.setWinNum(people.getWinNum()+1);
            //增加统计的金额
            if (mktReward.getRelevance() == 1){
                //如果存在关联商品,那么就需要查询出商品的价钱加上去
                MktProduct mktProduct = mktProductMapper.selectOne(new LambdaQueryWrapper<MktProduct>().eq(MktProduct::getId, mktReward.getProductId()));
                MktStatistics mktStatistics = mktStatisticsService.getOne(new LambdaQueryWrapper<MktStatistics>().eq(MktStatistics::getId, actId));

                mktStatistics.setMoneyTotal(mktStatistics.getMoneyTotal()+mktProduct.getPrice());

                mktStatisticsService.updateById(mktStatistics);

            }

        }

        mktPeopleMapper.updateById(people);

        //返回用户获得的奖品
        return mktReward;
    }

    @Override
    public boolean removeBatchByIds(Collection<?> list) {
        //在删除活动的时候也需要将营销活动统计表中的也删除
        mktStatisticsService.removeBatchByIds(list);
        return super.removeBatchByIds(list);
    }
}